home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 7 / Amiga Format AFCD07 (Dec 1996, Issue 91).iso / serious / shareware / programming / ixemul-complete / ixemul / general / glob.c < prev    next >
C/C++ Source or Header  |  1996-08-13  |  21KB  |  908 lines

  1. /*    $NetBSD: glob.c,v 1.5 1995/02/27 04:13:35 cgd Exp $    */
  2.  
  3. /*
  4.  * Copyright (c) 1989, 1993
  5.  *    The Regents of the University of California.  All rights reserved.
  6.  *
  7.  * This code is derived from software contributed to Berkeley by
  8.  * Guido van Rossum.
  9.  *
  10.  * Redistribution and use in source and binary forms, with or without
  11.  * modification, are permitted provided that the following conditions
  12.  * are met:
  13.  * 1. Redistributions of source code must retain the above copyright
  14.  *    notice, this list of conditions and the following disclaimer.
  15.  * 2. Redistributions in binary form must reproduce the above copyright
  16.  *    notice, this list of conditions and the following disclaimer in the
  17.  *    documentation and/or other materials provided with the distribution.
  18.  * 3. All advertising materials mentioning features or use of this software
  19.  *    must display the following acknowledgement:
  20.  *    This product includes software developed by the University of
  21.  *    California, Berkeley and its contributors.
  22.  * 4. Neither the name of the University nor the names of its contributors
  23.  *    may be used to endorse or promote products derived from this software
  24.  *    without specific prior written permission.
  25.  *
  26.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  27.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  28.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  29.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  30.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  31.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  32.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  33.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  34.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  35.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  36.  * SUCH DAMAGE.
  37.  */
  38.  
  39. #if defined(LIBC_SCCS) && !defined(lint)
  40. #if 0
  41. static char sccsid[] = "@(#)glob.c    8.3 (Berkeley) 10/13/93";
  42. #else
  43. static char rcsid[] = "$NetBSD: glob.c,v 1.5 1995/02/27 04:13:35 cgd Exp $";
  44. #endif
  45. #endif /* LIBC_SCCS and not lint */
  46.  
  47. /*
  48.  * glob(3) -- a superset of the one defined in POSIX 1003.2.
  49.  *
  50.  * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
  51.  *
  52.  * Optional extra services, controlled by flags not defined by POSIX:
  53.  *
  54.  * GLOB_QUOTE:
  55.  *    Escaping convention: \ inhibits any special meaning the following
  56.  *    character might have (except \ at end of string is retained).
  57.  * GLOB_MAGCHAR:
  58.  *    Set in gl_flags if pattern contained a globbing character.
  59.  * GLOB_NOMAGIC:
  60.  *    Same as GLOB_NOCHECK, but it will only append pattern if it did
  61.  *    not contain any magic characters.  [Used in csh style globbing]
  62.  * GLOB_ALTDIRFUNC:
  63.  *    Use alternately specified directory access functions.
  64.  * GLOB_TILDE:
  65.  *    expand ~user/foo to the /home/dir/of/user/foo
  66.  * GLOB_BRACE:
  67.  *    expand {1,2}{a,b} to 1a 1b 2a 2b 
  68.  * gl_matchc:
  69.  *    Number of matches in the current invocation of glob.
  70.  */
  71.  
  72. #define _KERNEL
  73. #include "ixemul.h"
  74. #include "kprintf.h"
  75.  
  76. #undef DEBUG
  77.  
  78. #include <sys/param.h>
  79. #include <sys/stat.h>
  80.  
  81. #include <ctype.h>
  82. #include <dirent.h>
  83. #include <errno.h>
  84. #include <glob.h>
  85. #include <pwd.h>
  86. #include <stdio.h>
  87. #include <stdlib.h>
  88. #include <string.h>
  89. #include <unistd.h>
  90.  
  91. #undef NOT    /* in <intuition/intuition.h> on AmigaDOS */
  92.  
  93. #define    DOLLAR        '$'
  94. #define    DOT        '.'
  95. #define    EOS        '\0'
  96. #define    LBRACKET    '['
  97. #define    NOT        '!'
  98. #define    QUESTION    '?'
  99. #define    QUOTE        '\\'
  100. #define    RANGE        '-'
  101. #define    RBRACKET    ']'
  102. #define    SEP        '/'
  103. #define    STAR        '*'
  104. #define    TILDE        '~'
  105. #define    UNDERSCORE    '_'
  106. #define    LBRACE        '{'
  107. #define    RBRACE        '}'
  108. #define    SLASH        '/'
  109. #define    COMMA        ','
  110. #define HASH            '#'
  111.  
  112. #ifndef DEBUG
  113.  
  114. #define    M_QUOTE        0x8000
  115. #define    M_PROTECT    0x4000
  116. #define    M_MASK        0xffff
  117. #define    M_ASCII        0x00ff
  118.  
  119. typedef u_short Char;
  120.  
  121. #else
  122.  
  123. #define    M_QUOTE        0x80
  124. #define    M_PROTECT    0x40
  125. #define    M_MASK        0xff
  126. #define    M_ASCII        0x7f
  127.  
  128. typedef char Char;
  129.  
  130. #endif
  131.  
  132.  
  133. #define    CHAR(c)        ((Char)((c)&M_ASCII))
  134. #define    META(c)        ((Char)((c)|M_QUOTE))
  135. #define    M_ALL        META('*')
  136. #define    M_END        META(']')
  137. #define    M_NOT        META('!')
  138. #define    M_ONE        META('?')
  139. #define    M_RNG        META('-')
  140. #define    M_SET        META('[')
  141. #define    ismeta(c)    (((c)&M_QUOTE) != 0)
  142.  
  143.  
  144. static int     compare __P((const void *, const void *));
  145. static int     icompare __P((const void *, const void *));
  146. static void     g_Ctoc __P((const Char *, char *));
  147. static int     g_lstat __P((Char *, struct stat *, glob_t *));
  148. static DIR    *g_opendir __P((Char *, glob_t *));
  149. static Char    *g_strchr __P((Char *, int));
  150. #ifdef notdef
  151. static Char    *g_strcat __P((Char *, const Char *));
  152. #endif
  153. static int     g_stat __P((Char *, struct stat *, glob_t *));
  154. static int     glob0 __P((const Char *, glob_t *));
  155. static int     glob1 __P((Char *, glob_t *));
  156. static int     glob2 __P((Char *, Char *, Char *, glob_t *));
  157. static int     glob3 __P((Char *, Char *, Char *, Char *, glob_t *));
  158. static int     globextend __P((const Char *, glob_t *));
  159. static const Char *     globtilde __P((const Char *, Char *, glob_t *));
  160. static int     globexp1 __P((const Char *, glob_t *));
  161. static int     globexp2 __P((const Char *, const Char *, glob_t *, int *));
  162. static int     match __P((Char *, Char *, Char *, int));
  163. #ifdef DEBUG
  164. static void     qprintf __P((const char *, Char *));
  165. #endif
  166.  
  167. DIR *opendir __P((const char *));
  168. struct dirent *readdir __P((DIR *));
  169. int closedir __P((DIR *));
  170.  
  171. int
  172. glob(pattern, flags, errfunc, pglob)
  173.     const char *pattern;
  174.     int flags, (*errfunc) __P((const char *, int));
  175.     glob_t *pglob;
  176. {
  177.     const u_char *patnext;
  178.     char *glob_pattern = (char *)pattern;
  179.     int c;
  180.     Char *bufnext, *bufend, patbuf[MAXPATHLEN+1];
  181.  
  182.         if (index(pattern, ':'))
  183.           {
  184.             char *colon;
  185.  
  186.             glob_pattern = alloca(strlen(pattern) + 2);
  187.             strcpy(glob_pattern + 1, pattern);
  188.             *glob_pattern = '/';
  189.             colon = index(glob_pattern, ':');
  190.             *colon = '/';
  191.           }
  192.     patnext = (u_char *) glob_pattern;
  193.     if (!(flags & GLOB_APPEND)) {
  194.         pglob->gl_pathc = 0;
  195.         pglob->gl_pathv = NULL;
  196.         if (!(flags & GLOB_DOOFFS))
  197.             pglob->gl_offs = 0;
  198.     }
  199.     pglob->gl_flags = flags & ~GLOB_MAGCHAR;
  200.     pglob->gl_errfunc = errfunc;
  201.     pglob->gl_matchc = 0;
  202.  
  203.     bufnext = patbuf;
  204.     bufend = bufnext + MAXPATHLEN;
  205.     if (flags & GLOB_QUOTE) {
  206.         /* Protect the quoted characters. */
  207.         while (bufnext < bufend && (c = *patnext++) != EOS) 
  208.             if (c == QUOTE) {
  209.                 if ((c = *patnext++) == EOS) {
  210.                     c = QUOTE;
  211.                     --patnext;
  212.                 }
  213.                 *bufnext++ = c | M_PROTECT;
  214.             }
  215.             else
  216.                 *bufnext++ = c;
  217.     }
  218.     else 
  219.         while (bufnext < bufend && (c = *patnext++) != EOS) 
  220.             *bufnext++ = c;
  221.     *bufnext = EOS;
  222.  
  223.     if (flags & GLOB_BRACE)
  224.         return globexp1(patbuf, pglob);
  225.     else
  226.         return glob0(patbuf, pglob);
  227. }
  228.  
  229. /*
  230.  * Expand recursively a glob {} pattern. When there is no more expansion
  231.  * invoke the standard globbing routine to glob the rest of the magic
  232.  * characters
  233.  */
  234. static int globexp1(pattern, pglob)
  235.     const Char *pattern;
  236.     glob_t *pglob;
  237. {
  238.     const Char* ptr = pattern;
  239.     int rv;
  240.  
  241.     /* Protect a single {}, for find(1), like csh */
  242.     if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
  243.         return glob0(pattern, pglob);
  244.  
  245.     while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL)
  246.         if (!globexp2(ptr, pattern, pglob, &rv))
  247.             return rv;
  248.  
  249.     return glob0(pattern, pglob);
  250. }
  251.  
  252.  
  253. /*
  254.  * Recursive brace globbing helper. Tries to expand a single brace.
  255.  * If it succeeds then it invokes globexp1 with the new pattern.
  256.  * If it fails then it tries to glob the rest of the pattern and returns.
  257.  */
  258. static int globexp2(ptr, pattern, pglob, rv)
  259.     const Char *ptr, *pattern;
  260.     glob_t *pglob;
  261.     int *rv;
  262. {
  263.     int     i;
  264.     Char   *lm, *ls;
  265.     const Char *pe, *pm, *pl;
  266.     Char    patbuf[MAXPATHLEN + 1];
  267.  
  268.     /* copy part up to the brace */
  269.     for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
  270.         continue;
  271.     ls = lm;
  272.  
  273.     /* Find the balanced brace */
  274.     for (i = 0, pe = ++ptr; *pe; pe++)
  275.         if (*pe == LBRACKET) {
  276.             /* Ignore everything between [] */
  277.             for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
  278.                 continue;
  279.             if (*pe == EOS) {
  280.                 /* 
  281.                  * We could not find a matching RBRACKET.
  282.                  * Ignore and just look for RBRACE
  283.                  */
  284.                 pe = pm;
  285.             }
  286.         }
  287.         else if (*pe == LBRACE)
  288.             i++;
  289.         else if (*pe == RBRACE) {
  290.             if (i == 0)
  291.                 break;
  292.             i--;
  293.         }
  294.  
  295.     /* Non matching braces; just glob the pattern */
  296.     if (i != 0 || *pe == EOS) {
  297.         *rv = glob0(patbuf, pglob);
  298.         return 0;
  299.     }
  300.  
  301.     for (i = 0, pl = pm = ptr; pm <= pe; pm++)
  302.         switch (*pm) {
  303.         case LBRACKET:
  304.             /* Ignore everything between [] */
  305.             for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
  306.                 continue;
  307.             if (*pm == EOS) {
  308.                 /* 
  309.                  * We could not find a matching RBRACKET.
  310.                  * Ignore and just look for RBRACE
  311.                  */
  312.                 pm = pl;
  313.             }
  314.             break;
  315.  
  316.         case LBRACE:
  317.             i++;
  318.             break;
  319.  
  320.         case RBRACE:
  321.             if (i) {
  322.                 i--;
  323.                 break;
  324.             }
  325.             /* FALLTHROUGH */
  326.         case COMMA:
  327.             if (i && *pm == COMMA)
  328.                 break;
  329.             else {
  330.                 /* Append the current string */
  331.                 for (lm = ls; (pl < pm); *lm++ = *pl++)
  332.                     continue;
  333.                 /* 
  334.                  * Append the rest of the pattern after the
  335.                  * closing brace
  336.                  */
  337.                 for (pl = pe + 1; (*lm++ = *pl++) != EOS;)
  338.                     continue;
  339.  
  340.                 /* Expand the current pattern */
  341. #ifdef DEBUG
  342.                 qprintf("globexp2:", patbuf);
  343. #endif
  344.                 *rv = globexp1(patbuf, pglob);
  345.  
  346.                 /* move after the comma, to the next string */
  347.                 pl = pm + 1;
  348.             }
  349.             break;
  350.  
  351.         default:
  352.             break;
  353.         }
  354.     *rv = 0;
  355.     return 0;
  356. }
  357.  
  358.  
  359.  
  360. /*
  361.  * expand tilde from the passwd file.
  362.  */
  363. static const Char *
  364. globtilde(pattern, patbuf, pglob)
  365.     const Char *pattern;
  366.     Char *patbuf;
  367.     glob_t *pglob;
  368. {
  369.     struct passwd *pwd;
  370.     char *h;
  371.     const Char *p;
  372.     Char *b;
  373.  
  374.     if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
  375.         return pattern;
  376.  
  377.     /* Copy up to the end of the string or / */
  378.     for (p = pattern + 1, h = (char *) patbuf; *p && *p != SLASH; 
  379.          *h++ = *p++)
  380.         continue;
  381.  
  382.     *h = EOS;
  383.  
  384.     if (((char *) patbuf)[0] == EOS) {
  385.         /* 
  386.          * handle a plain ~ or ~/ by expanding $HOME 
  387.          * first and then trying the password file
  388.          */
  389.         if ((h = getenv("HOME")) == NULL) {
  390.             if ((pwd = getpwuid(getuid())) == NULL)
  391.                 return pattern;
  392.             else
  393.                 h = pwd->pw_dir;
  394.         }
  395.     }
  396.     else {
  397.         /*
  398.          * Expand a ~user
  399.          */
  400.         if ((pwd = getpwnam((char*) patbuf)) == NULL)
  401.             return pattern;
  402.         else
  403.             h = pwd->pw_dir;
  404.     }
  405.  
  406.     /* Copy the home directory */
  407.     for (b = patbuf; *h; *b++ = *h++)
  408.         continue;
  409.     
  410.     /* Append the rest of the pattern */
  411.     while ((*b++ = *p++) != EOS)
  412.         continue;
  413.  
  414.     return patbuf;
  415. }
  416.     
  417.  
  418. /*
  419.  * The main glob() routine: compiles the pattern (optionally processing
  420.  * quotes), calls glob1() to do the real pattern matching, and finally
  421.  * sorts the list (unless unsorted operation is requested).  Returns 0
  422.  * if things went well, nonzero if errors occurred.  It is not an error
  423.  * to find no matches.
  424.  */
  425. static int
  426. glob0(pattern, pglob)
  427.     const Char *pattern;
  428.     glob_t *pglob;
  429. {
  430.     const Char *qpatnext;
  431.     int c, err, oldpathc;
  432.     Char *bufnext, patbuf[MAXPATHLEN+1];
  433.  
  434.     qpatnext = globtilde(pattern, patbuf, pglob);
  435.     oldpathc = pglob->gl_pathc;
  436.     bufnext = patbuf;
  437.  
  438.     /* We don't need to check for buffer overflow any more. */
  439.     while ((c = *qpatnext++) != EOS) {
  440.         switch (c) {
  441.         case LBRACKET:
  442.             c = *qpatnext;
  443.             if (c == NOT)
  444.                 ++qpatnext;
  445.             if (*qpatnext == EOS ||
  446.                 g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) {
  447.                 *bufnext++ = LBRACKET;
  448.                 if (c == NOT)
  449.                     --qpatnext;
  450.                 break;
  451.             }
  452.             *bufnext++ = M_SET;
  453.             if (c == NOT)
  454.                 *bufnext++ = M_NOT;
  455.             c = *qpatnext++;
  456.             do {
  457.                 *bufnext++ = CHAR(c);
  458.                 if (*qpatnext == RANGE &&
  459.                     (c = qpatnext[1]) != RBRACKET) {
  460.                     *bufnext++ = M_RNG;
  461.                     *bufnext++ = CHAR(c);
  462.                     qpatnext += 2;
  463.                 }
  464.             } while ((c = *qpatnext++) != RBRACKET);
  465.             pglob->gl_flags |= GLOB_MAGCHAR;
  466.             *bufnext++ = M_END;
  467.             break;
  468.         case QUESTION:
  469.             pglob->gl_flags |= GLOB_MAGCHAR;
  470.             *bufnext++ = M_ONE;
  471.             break;
  472.         case STAR:
  473.             pglob->gl_flags |= GLOB_MAGCHAR;
  474.             /* collapse adjacent stars to one, 
  475.              * to avoid exponential behavior
  476.              */
  477.             if (bufnext == patbuf || bufnext[-1] != M_ALL)
  478.                 *bufnext++ = M_ALL;
  479.             break;
  480.         case HASH:
  481.             if ((pglob->gl_flags & GLOB_AMIGA) && *qpatnext == QUESTION)
  482.             {
  483.               qpatnext++;
  484.               pglob->gl_flags |= GLOB_MAGCHAR;
  485.               if (bufnext == patbuf || bufnext[-1] != M_ALL)
  486.                 *bufnext++ = M_ALL;
  487.               break;
  488.             }
  489.             /* fall through */
  490.         default:
  491.             *bufnext++ = CHAR(c);
  492.             break;
  493.         }
  494.     }
  495.     *bufnext = EOS;
  496. #ifdef DEBUG
  497.     qprintf("glob0:", patbuf);
  498. #endif
  499.  
  500.     if ((err = glob1(patbuf, pglob)) != 0)
  501.         return(err);
  502.  
  503.     /*
  504.      * If there was no match we are going to append the pattern 
  505.      * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
  506.      * and the pattern did not contain any magic characters
  507.      * GLOB_NOMAGIC is there just for compatibility with csh.
  508.      */
  509.     if (pglob->gl_pathc == oldpathc && 
  510.         ((pglob->gl_flags & GLOB_NOCHECK) || 
  511.           ((pglob->gl_flags & GLOB_NOMAGIC) &&
  512.            !(pglob->gl_flags & GLOB_MAGCHAR))))
  513.         return(globextend(pattern, pglob));
  514.     else if (!(pglob->gl_flags & GLOB_NOSORT)) 
  515.         qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
  516.             pglob->gl_pathc - oldpathc, sizeof(char *), 
  517.                     (pglob->gl_flags & GLOB_NOCASE) ? icompare : compare);
  518.     return(0);
  519. }
  520.  
  521. static int
  522. compare(p, q)
  523.     const void *p, *q;
  524. {
  525.     return(strcmp(*(char **)p, *(char **)q));
  526. }
  527.  
  528. static int
  529. icompare(p, q)
  530.     const void *p, *q;
  531. {
  532.     return(strcasecmp(*(char **)p, *(char **)q));
  533. }
  534.  
  535. static int
  536. glob1(pattern, pglob)
  537.     Char *pattern;
  538.     glob_t *pglob;
  539. {
  540.     Char pathbuf[MAXPATHLEN+1];
  541.  
  542.     /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
  543.     if (*pattern == EOS)
  544.         return(0);
  545.     return(glob2(pathbuf, pathbuf, pattern, pglob));
  546. }
  547.  
  548. /*
  549.  * The functions glob2 and glob3 are mutually recursive; there is one level
  550.  * of recursion for each segment in the pattern that contains one or more
  551.  * meta characters.
  552.  */
  553. static int
  554. glob2(pathbuf, pathend, pattern, pglob)
  555.     Char *pathbuf, *pathend, *pattern;
  556.     glob_t *pglob;
  557. {
  558.     struct stat sb;
  559.     Char *p, *q;
  560.     int anymeta;
  561.  
  562.     /*
  563.      * Loop over pattern segments until end of pattern or until
  564.      * segment with meta character found.
  565.      */
  566.     for (anymeta = 0;;) {
  567.         if (*pattern == EOS) {        /* End of pattern? */
  568.             *pathend = EOS;
  569.             if (g_lstat(pathbuf, &sb, pglob))
  570.                 return(0);
  571.         
  572.             if (((pglob->gl_flags & GLOB_MARK) &&
  573.                 pathend[-1] != SEP) && (S_ISDIR(sb.st_mode)
  574.                 || (S_ISLNK(sb.st_mode) &&
  575.                 (g_stat(pathbuf, &sb, pglob) == 0) &&
  576.                 S_ISDIR(sb.st_mode)))) {
  577.                 *pathend++ = SEP;
  578.                 *pathend = EOS;
  579.             }
  580.             ++pglob->gl_matchc;
  581.             return(globextend(pathbuf, pglob));
  582.         }
  583.  
  584.         /* Find end of next segment, copy tentatively to pathend. */
  585.         q = pathend;
  586.         p = pattern;
  587.         while (*p != EOS && *p != SEP) {
  588.             if (ismeta(*p))
  589.                 anymeta = 1;
  590.             *q++ = *p++;
  591.         }
  592.  
  593.         if (!anymeta) {        /* No expansion, do next segment. */
  594.             pathend = q;
  595.             pattern = p;
  596.             while (*pattern == SEP)
  597.                 *pathend++ = *pattern++;
  598.         } else            /* Need expansion, recurse. */
  599.             return(glob3(pathbuf, pathend, pattern, p, pglob));
  600.     }
  601.     /* NOTREACHED */
  602. }
  603.  
  604. static int
  605. glob3(pathbuf, pathend, pattern, restpattern, pglob)
  606.     Char *pathbuf, *pathend, *pattern, *restpattern;
  607.     glob_t *pglob;
  608. {
  609.     register struct dirent *dp;
  610.     DIR *dirp;
  611.     int err;
  612.     char buf[MAXPATHLEN];
  613.  
  614.     /*
  615.      * The readdirfunc declaration can't be prototyped, because it is
  616.      * assigned, below, to two functions which are prototyped in glob.h
  617.      * and dirent.h as taking pointers to differently typed opaque
  618.      * structures.
  619.      */
  620.     struct dirent *(*readdirfunc)();
  621.  
  622.     *pathend = EOS;
  623.     errno = 0;
  624.         
  625.     if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
  626.         /* TODO: don't call for ENOENT or ENOTDIR? */
  627.         if (pglob->gl_errfunc) {
  628.             g_Ctoc(pathbuf, buf);
  629.             if (pglob->gl_errfunc(buf, errno) ||
  630.                 pglob->gl_flags & GLOB_ERR)
  631.                 return (GLOB_ABEND);
  632.         }
  633.         return(0);
  634.     }
  635.  
  636.     err = 0;
  637.  
  638.     /* Search directory for matching names. */
  639.     if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  640.         readdirfunc = pglob->gl_readdir;
  641.     else
  642.         readdirfunc = readdir;
  643.     while ((dp = (*readdirfunc)(dirp))) {
  644.         register u_char *sc;
  645.         register Char *dc;
  646.  
  647.         /* Initial DOT must be matched literally. */
  648.         if (dp->d_name[0] == DOT && *pattern != DOT)
  649.             continue;
  650.         for (sc = (u_char *) dp->d_name, dc = pathend; 
  651.              (*dc++ = *sc++) != EOS;)
  652.             continue;
  653.         if (!match(pathend, pattern, restpattern, pglob->gl_flags & GLOB_NOCASE)) {
  654.             *pathend = EOS;
  655.             continue;
  656.         }
  657.         err = glob2(pathbuf, --dc, restpattern, pglob);
  658.         if (err)
  659.             break;
  660.     }
  661.  
  662.     if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  663.         (*pglob->gl_closedir)(dirp);
  664.     else
  665.         closedir(dirp);
  666.     return(err);
  667. }
  668.  
  669.  
  670. /*
  671.  * Extend the gl_pathv member of a glob_t structure to accomodate a new item,
  672.  * add the new item, and update gl_pathc.
  673.  *
  674.  * This assumes the BSD realloc, which only copies the block when its size
  675.  * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
  676.  * behavior.
  677.  *
  678.  * Return 0 if new item added, error code if memory couldn't be allocated.
  679.  *
  680.  * Invariant of the glob_t structure:
  681.  *    Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
  682.  *    gl_pathv points to (gl_offs + gl_pathc + 1) items.
  683.  */
  684. static int
  685. globextend(path, pglob)
  686.     const Char *path;
  687.     glob_t *pglob;
  688. {
  689.     register char **pathv;
  690.     register int i;
  691.     u_int newsize;
  692.     char *copy;
  693.     const Char *p;
  694.  
  695.     newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
  696.     pathv = pglob->gl_pathv ? 
  697.             realloc((char *)pglob->gl_pathv, newsize) :
  698.             malloc(newsize);
  699.     if (pathv == NULL)
  700.         return(GLOB_NOSPACE);
  701.  
  702.     if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
  703.         /* first time around -- clear initial gl_offs items */
  704.         pathv += pglob->gl_offs;
  705.         for (i = pglob->gl_offs; --i >= 0; )
  706.             *--pathv = NULL;
  707.     }
  708.     pglob->gl_pathv = pathv;
  709.  
  710.     for (p = path; *p++;)
  711.         continue;
  712.     if ((copy = malloc(p - path)) != NULL) {
  713.         g_Ctoc(path, copy);
  714.         pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
  715.     }
  716.     pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
  717.     return(copy == NULL ? GLOB_NOSPACE : 0);
  718. }
  719.  
  720.  
  721. /*
  722.  * pattern matching function for filenames.  Each occurrence of the *
  723.  * pattern causes a recursion level.
  724.  */
  725. static int
  726. match(name, pat, patend, nocase)
  727.     register Char *name, *pat, *patend;
  728.         int nocase;
  729. {
  730.     int ok, negate_range;
  731.     Char c, k;
  732.  
  733.     while (pat < patend) {
  734.         c = *pat++;
  735.         switch (c & M_MASK) {
  736.         case M_ALL:
  737.             if (pat == patend)
  738.                 return(1);
  739.             do 
  740.                 if (match(name, pat, patend, nocase))
  741.                     return(1);
  742.             while (*name++ != EOS);
  743.             return(0);
  744.         case M_ONE:
  745.             if (*name++ == EOS)
  746.                 return(0);
  747.             break;
  748.         case M_SET:
  749.             ok = 0;
  750.             if ((k = *name++) == EOS)
  751.                 return(0);
  752.             if (nocase)
  753.               k = tolower(k);
  754.             if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
  755.                 ++pat;
  756.             while (((c = *pat++) & M_MASK) != M_END) {
  757.                     if (nocase)
  758.                             c = tolower(c);
  759.                 if ((*pat & M_MASK) == M_RNG) {
  760.                     if (c <= k && k <= (nocase ? tolower(pat[1]) : pat[1]))
  761.                         ok = 1;
  762.                     pat += 2;
  763.                 } else if (c == k)
  764.                     ok = 1;
  765.             }
  766.             if (ok == negate_range)
  767.                 return(0);
  768.             break;
  769.         default:
  770.                 if (nocase)
  771.                 {
  772.                   k = *name++;
  773.                   if (tolower(k) != tolower(c))
  774.                     return 0;
  775.                 }
  776.             else if (*name++ != c)
  777.                 return(0);
  778.             break;
  779.         }
  780.     }
  781.     return(*name == EOS);
  782. }
  783.  
  784. /* Free allocated data belonging to a glob_t structure. */
  785. void
  786. globfree(pglob)
  787.     glob_t *pglob;
  788. {
  789.     register int i;
  790.     register char **pp;
  791.  
  792.     if (pglob->gl_pathv != NULL) {
  793.         pp = pglob->gl_pathv + pglob->gl_offs;
  794.         for (i = pglob->gl_pathc; i--; ++pp)
  795.             if (*pp)
  796.                 free(*pp);
  797.         free(pglob->gl_pathv);
  798.     }
  799. }
  800.  
  801. static DIR *
  802. g_opendir(str, pglob)
  803.     register Char *str;
  804.     glob_t *pglob;
  805. {
  806.     char buf[MAXPATHLEN];
  807.  
  808.     if (!*str)
  809.         strcpy(buf, ".");
  810.     else
  811.         g_Ctoc(str, buf);
  812.  
  813.     if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  814.         return((*pglob->gl_opendir)(buf));
  815.  
  816.     return(opendir(buf));
  817. }
  818.  
  819. static int
  820. g_lstat(fn, sb, pglob)
  821.     register Char *fn;
  822.     struct stat *sb;
  823.     glob_t *pglob;
  824. {
  825.     char buf[MAXPATHLEN];
  826.  
  827.     g_Ctoc(fn, buf);
  828.     if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  829.         return((*pglob->gl_lstat)(buf, sb));
  830.     return(lstat(buf, sb));
  831. }
  832.  
  833. static int
  834. g_stat(fn, sb, pglob)
  835.     register Char *fn;
  836.     struct stat *sb;
  837.     glob_t *pglob;
  838. {
  839.     char buf[MAXPATHLEN];
  840.  
  841.     g_Ctoc(fn, buf);
  842.     if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  843.         return((*pglob->gl_stat)(buf, sb));
  844.     return(stat(buf, sb));
  845. }
  846.  
  847. static Char *
  848. g_strchr(str, ch)
  849.     Char *str;
  850.     int ch;
  851. {
  852.     do {
  853.         if (*str == ch)
  854.             return (str);
  855.     } while (*str++);
  856.     return (NULL);
  857. }
  858.  
  859. #ifdef notdef
  860. static Char *
  861. g_strcat(dst, src)
  862.     Char *dst;
  863.     const Char* src;
  864. {
  865.     Char *sdst = dst;
  866.  
  867.     while (*dst++)
  868.         continue;
  869.     --dst;
  870.     while((*dst++ = *src++) != EOS)
  871.         continue;
  872.  
  873.     return (sdst);
  874. }
  875. #endif
  876.  
  877. static void
  878. g_Ctoc(str, buf)
  879.     register const Char *str;
  880.     char *buf;
  881. {
  882.     register char *dc;
  883.  
  884.     for (dc = buf; (*dc++ = *str++) != EOS;)
  885.         continue;
  886. }
  887.  
  888. #ifdef DEBUG
  889. static void 
  890. qprintf(str, s)
  891.     const char *str;
  892.     register Char *s;
  893. {
  894.     register Char *p;
  895.  
  896.     (void)printf("%s:\n", str);
  897.     for (p = s; *p; p++)
  898.         (void)printf("%c", CHAR(*p));
  899.     (void)printf("\n");
  900.     for (p = s; *p; p++)
  901.         (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
  902.     (void)printf("\n");
  903.     for (p = s; *p; p++)
  904.         (void)printf("%c", ismeta(*p) ? '_' : ' ');
  905.     (void)printf("\n");
  906. }
  907. #endif
  908.